package Chapter16.ticket;

/**
 * @author 杨森
 * @date 2022年10月30日 21:08
 * 使用多线程，模拟三个窗口同时售票100张
 */
public class SellTicket {
    public static void main(String[] args) {
//        SellTicket01 sellTicket01 = new SellTicket01();
//        SellTicket01 sellTicket02 = new SellTicket01();
//        SellTicket01 sellTicket03 = new SellTicket01();
////        会出现超卖的现象
//        sellTicket01.start();
//        sellTicket02.start();
//        sellTicket03.start();

//还会出现超卖现象
        SellTicket02 sellTicket02 = new SellTicket02();
        new Thread(sellTicket02).start();
        new Thread(sellTicket02).start();
        new Thread(sellTicket02).start();
    }
}

//使用Thread方式
class SellTicket01 extends Thread {
    private static int ticketnum = 100;//让多个线程共享ticketNum

    @Override
    public void run() {
        while (true) {
            if (ticketnum <= 0) {
                System.out.println("售票结束...");
                break;
            }

            try {
                Thread.sleep(50);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("窗口" + Thread.currentThread()
                    .getName() + "售出一张票" + "剩余票数="
                    + (--ticketnum));
        }
    }
}

//使用接口方式
class SellTicket02 implements Runnable {
    private int ticketnum = 100;//让多个线程共享ticketNum

    @Override
    public void run() {
        while (true) {
            if (ticketnum <= 0) {
                System.out.println("售票结束...");
                break;
            }

            try {
                Thread.sleep(50);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("窗口" + Thread.currentThread()
                    .getName() + "售出一张票" + "剩余票数="
                    + (--ticketnum));
        }
    }
}

